from django.db import models


class ModelMeta(models.Model):
    STATUS_CHOICE = [
        (1, "有效"),
        (0, "无效")
    ]
    name = models.CharField(max_length=50, null=True, blank=True,
                            default=' ')
    order_no = models.CharField(max_length=50, unique=True, null=True, default=' ')
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.IntegerField(default=0, choices=STATUS_CHOICE, max_length=2)
    # json_data = models.JSONField(null=True)  # 存储json 字段  mysql 5.7.8+ 才支持次格式

    class Meta:
        # 模型属性
        verbose_name = '数据库表备注名称'  # 指定数据表备注名称
        db_table = 'apis_model_meta'  # 数据表
        ordering = ['-id']  # 排序
        indexes = [
            models.Index(fields=['name']),  # 指定索引
            models.Index(fields=['created'])  # 指定索引
        ]
        constraints = [
            # models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'), # 级联约束
        ]

    # 模型方法
    def pretty_date(self):
        time = self.created
        """
        Get a datetime object or a int() Epoch timestamp and return a
        pretty string like 'an hour ago', 'Yesterday', '3 months ago',
        'just now', etc
        """
        from datetime import datetime
        now = datetime.now()
        if type(time) is int:
            diff = now - datetime.fromtimestamp(time)
        elif isinstance(time, datetime):
            diff = now - time
        elif not time:
            diff = now - now
        second_diff = diff.seconds
        day_diff = diff.days

        if day_diff < 0:
            return ''

        if day_diff == 0:
            if second_diff < 10:
                return "just now"
            if second_diff < 60:
                return str(second_diff) + " seconds ago"
            if second_diff < 120:
                return "a minute ago"
            if second_diff < 3600:
                return str(int(second_diff / 60)) + " minutes ago"
            if second_diff < 7200:
                return "an hour ago"
            if second_diff < 86400:
                return str(int(second_diff / 3600)) + " hours ago"
        if day_diff == 1:
            return "Yesterday"
        if day_diff < 7:
            return str(day_diff) + " days ago"
        if day_diff < 31:
            return str(int(day_diff / 7)) + " weeks ago"
        if day_diff < 365:
            return str(int(day_diff / 30)) + " months ago"
        return str(int(day_diff / 365)) + " years ago"

    @property
    def name_order_no(self):
        return 'name： %s, order_no：%s' % (self.name, self.order_no)

    def __str__(self):
        return 'id：%s,name： %s, order_no：%s' % (self.id, self.name, self.order_no)
